using System;
using System.IO;
using CodePlex.DnD4eCampaignManager.CampaignManagerTests.TestUtilities;
using CodePlex.DnD4eCampaignManager.DnD4e.Interfaces;
using CodePlex.DnD4eCampaignManager.Repositories;
using CodePlex.DnD4eCampaignManager.Repositories.XmlRepositories;
using NUnit.Framework;

namespace CodePlex.DnD4eCampaignManager.CampaignManagerTests.RepositoryTests
{
    [TestFixture]
    public class PlayerCharacterRepositoryTests
    {
        private IPlayerCharacter _playerCharacter;
        private IPlayerCharacterRepository _playerCharacterRepository;

        [Test]
        public void GetAllNamesReturnsTheFileNamesOfAllDotPcFilesInTheCharactersFolder()
        {
            Assert.AreEqual(Directory.GetFiles("Characters", "*.pc").Length, _playerCharacterRepository.GetAllNames().Count);
        }

        [Test]
        public void GetByNameRestoresPreviouslySavedCharacters()
        {
            _playerCharacterRepository.Save(_playerCharacter);
            IPlayerCharacter playerCharacterFromFile = _playerCharacterRepository.GetByName(_playerCharacter.Name);
            Assert.AreEqual(_playerCharacter, playerCharacterFromFile);
        }

        [Test]
        public void PlayerCharacterRepositoryLoadRestoresTheCharacterExactlyAsSaved()
        {
            _playerCharacterRepository.Save(_playerCharacter);
            IPlayerCharacter loadedCharacter = _playerCharacterRepository.GetByName(_playerCharacter.Name);
            Assert.AreEqual(_playerCharacter, loadedCharacter);
        }

        [Test]
        public void SaveCreatesAFileInTheCharactersFolder()
        {
            if ( File.Exists(string.Format("Characters\\{0}.pc", _playerCharacter.Name)) )
            {
                File.Delete(string.Format("Characters\\{0}.pc", _playerCharacter.Name));
            }
            Assert.IsFalse(File.Exists(string.Format("Characters\\{0}.pc", _playerCharacter.Name)));
            _playerCharacterRepository.Save(_playerCharacter);
            Assert.IsTrue(File.Exists(string.Format("Characters\\{0}.pc", _playerCharacter.Name)));
        }

        [Test]
        public void SaveTimeIsWithinAcceptableTime()
        {
            DateTime startTime = DateTime.Now;
            _playerCharacterRepository.Save(_playerCharacter);
            DateTime endTime = DateTime.Now;
            double saveTimeInMilliseconds = endTime.Subtract(startTime).TotalMilliseconds;
            Console.Out.WriteLine("saveTimeInMilliseconds = {0}", saveTimeInMilliseconds);
            Assert.Less(saveTimeInMilliseconds, 50);
        }

        [SetUp]
        public void SetUp()
        {
            _playerCharacter = DefaultTestObjects.TestPlayerCharacter();
            _playerCharacterRepository = new PlayerCharacterXmlRepository();
        }
    }
}